import { AddButton } from '@app-nextmesh/components';
import { TYPE_BOOL, TYPE_DOUBLE, TYPE_INT } from '@app-nextmesh/types';
import { Box, Collapse, Stack } from '@mui/material';
import { cloneDeep, isArray } from 'lodash';
import { useEffect, useState } from 'react';
import Forluma from '../Formula';
import Checkbox from './Checkbox';
import ErrorTips from './ErrorTips';
import Label from './Label';
import SwitchToggle from './SwitchToggle';
import UnitSelect from './UnitSelect';
import ValueInput from './ValueInput';
import { IBaseProps } from './types';

type FormType = { Unit?: string; Value: any[] };
interface IProps extends IBaseProps<FormType> {
  type: string; // xArrayb, Arrayb 等
  label?: string;
  disabled: boolean;
  units?: string[];
}
const LABELS = ['X', 'Y', 'Z'];
/**
 * 向量及其单位设置和选择 组件
 */
export default function ArrayN({
  value: initValue,
  type,
  label,
  disabled,
  units,
  onChange: onInputChange,
}: IProps) {
  const [value, setValue] = useState(initValue);
  const [showFormula, setShowFormula] = useState({
    name: '',
    value: '',
    open: false,
  });
  const [collapsed, setCollapsed] = useState(false);
  useEffect(() => {
    setValue(initValue);
  }, [initValue]);
  if (!initValue) {
    return <></>;
  }
  const handleValueChange = (index: number, v: number | boolean | any) => {
    const newValue = { ...value };
    newValue.Value[index] = v;
    setValue(newValue);
    onInputChange(newValue);
  };
  const handleAdd = () => {
    const newValue = { ...value };
    if (type.endsWith('b')) {
      // boolean
      newValue.Value.push(true);
    } else {
      // double int
      newValue.Value.push(0);
    }
    setValue(newValue);
    onInputChange(newValue);
  };
  const handleUnitChange = (unit: string) => {
    // 多个输入项单位保持一致
    const newValue = cloneDeep(value);
    newValue.Unit = unit;
    setValue(newValue);
    onInputChange(newValue);
  };
  const handleClick = () => {
    setCollapsed((c) => !c);
  };
  let numberType = TYPE_DOUBLE;
  if (type.endsWith('b')) {
    numberType = TYPE_BOOL;
  } else if (type.endsWith('i')) {
    numberType = TYPE_INT;
  } else {
    numberType = TYPE_DOUBLE;
  }
  const isUnoin = type.includes('Unoin');
  const isNoTitle = type.includes('NoTitle');
  const isNoLabel = type.includes('NoLabel');
  return (
    <>
      <Box sx={{ mt: 1 }}>
        <Box
          sx={{
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'space-between',
          }}>
          <Stack
            sx={{ width: '50%', cursor: 'pointer' }}
            direction='row'
            alignItems='center'
            onClick={handleClick}>
            <SwitchToggle toggle={collapsed} />
            <label style={{ fontWeight: 'bold', marginLeft: '5px' }}>
              {label}
            </label>
          </Stack>
          <UnitSelect
            disabled={disabled}
            units={units}
            value={value.Unit}
            onChange={handleUnitChange}
          />
        </Box>
        <Collapse
          in={!collapsed}
          sx={{ pl: '14px' }}>
          {isArray(value.Value) ? (
            value.Value.map((value, index) => {
              const label = !isNoTitle
                ? !isNoLabel
                  ? (LABELS[index] ?? '' + index)
                  : ''
                : 'DOF' + (index + 1);
              let disabled2 = false;
              let v = value;
              let handleChange = (value) => {
                handleValueChange(index, value);
              };
              if (isUnoin) {
                // 如果是关联选项，disabled为value.isPrescribed
                disabled2 = !value.isPrescribed;
                v = value.value;
                handleChange = (value2) => {
                  handleValueChange(index, {
                    isPrescribed: value.isPrescribed,
                    value: value2,
                  });
                };
              }
              disabled2 = disabled || disabled2;
              let inputCol = (
                <Stack
                  key={index}
                  direction='row'
                  alignItems='center'
                  justifyContent='space-between'>
                  <div style={{ minWidth: '50%' }}>
                    {!isNoTitle ? (
                      <Label label={label} />
                    ) : (
                      <Checkbox
                        disabled={disabled}
                        label={label}
                        checked={value.isPrescribed}
                        onChange={(checked) => {
                          handleValueChange(index, {
                            isPrescribed: checked,
                            value: value.value,
                          });
                        }}
                      />
                    )}
                  </div>
                  <ValueInput
                    type={numberType}
                    value={v}
                    disabled={disabled2}
                    onChange={handleChange}
                  />
                  {/* <SmallButton onClick={() => { setShowFormula({ name: '' + index, value, open: true }) }}>
                      <Latex>{'$\\sqrt{x}$'}</Latex>
                    </SmallButton> */}
                </Stack>
              );
              if (isUnoin) {
                inputCol = (
                  <Stack
                    key={index}
                    direction='column'>
                    {!isNoTitle ? (
                      <Checkbox
                        disabled={disabled}
                        label={`在 ${label} 方向上指定`}
                        checked={value.isPrescribed}
                        onChange={(checked) => {
                          handleValueChange(index, {
                            isPrescribed: checked,
                            value: value.value,
                          });
                        }}
                      />
                    ) : (
                      inputCol
                    )}
                  </Stack>
                );
              }
              return inputCol;
            })
          ) : (
            <ErrorTips>{`格式错误，无效的Default：${JSON.stringify(value.Value)}`}</ErrorTips>
          )}
          {type.startsWith('x') && (
            <AddButton
              key={value.Value.length}
              onClick={handleAdd}
            />
          )}
        </Collapse>
      </Box>
      <Forluma
        name={showFormula.name}
        value={showFormula.value}
        open={showFormula.open}
        onOk={(v) => onInputChange(v)}
        onClose={() => {
          setShowFormula({ ...showFormula, open: false });
        }}
      />
    </>
  );
}
